package com.gz.steak.common.aspect;

import com.gz.steak.common.aspect.anotation.LoginLog;
import com.gz.steak.common.exception.BusinessException;
import com.gz.steak.utils.convert.ConvertUtil;
import com.gz.steak.common.web.result.Result;
import com.gz.steak.modules.system.mapper.SysLoginLogMapper;
import com.gz.steak.modules.system.pojo.dataobject.SysLoginLog;
import com.gz.steak.modules.system.service.SysLoginLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @Author 刘牌
 * @Date 2020/3/22 0022 11:09
 * @Version 1.0
 */
@Component
@Aspect
public class LoginLogAspect {
    private final static Logger logger = LoggerFactory.getLogger(LoginLogAspect.class);

    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SysLoginLogMapper sysLoginLogMapper;
    @Autowired
    private SysLoginLogService sysLoginLogService;

    @Pointcut("@annotation(loginLog)")
    public void  loginLog(LoginLog loginLog){}

    @Around("loginLog(log)")
    public Object doLoginLog(ProceedingJoinPoint point,LoginLog log) throws Throwable {
        return point.proceed();
    }

    /**
     * 发生异常
     * @param log
     * @param ex
     */
    @AfterThrowing(pointcut = "loginLog(log)" , throwing = "ex")
    public void exception(LoginLog log, BusinessException ex){
        String username = (String) request.getSession().getAttribute("username");
        SysLoginLog sysLoginLog = new SysLoginLog();
        sysLoginLog.setIp(request.getRemoteAddr())
                .setLoginTime(ConvertUtil.FormatDate(new Date()))
                .setOperation(ex.getErrorMsg())
                .setStatus("登录失败")
                .setUserName(username);
        sysLoginLogService.save(sysLoginLog);
    }

    /**
     * 成功执行
     * @param log
     * @param s
     */
    @AfterReturning(pointcut = "loginLog(log)",returning = "s")
    public void success(LoginLog log , Result s){
        String username = (String) request.getSession().getAttribute("username");
        SysLoginLog sysLoginLog = new SysLoginLog();
        sysLoginLog.setUserName(username)
                .setStatus("登录成功")
                .setOperation("成功")
                .setLoginTime(ConvertUtil.FormatDate(new Date()))
                .setIp(request.getRemoteAddr());
        sysLoginLogService.save(sysLoginLog);
    }
}
